package com.mxdx.edu.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.mxdx.edu.constant.StaticConstants;
import com.mxdx.edu.enums.SalesManTypeEnums;
import com.mxdx.edu.enums.StudentTypeEnums;

import com.mxdx.edu.model.UserJobSeekerInfo;
import com.mxdx.edu.service.IUserJobBasisSeekerService;
import com.mxdx.edu.service.IUserJobSeekerService;
import org.springframework.stereotype.Component;

import com.mxdx.edu.common.CommonUtils;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.service.ISalesManInfoService;
import com.mxdx.edu.service.IStudentService;
import com.mxdx.edu.service.impl.SalesManInfoServiceImpl;
import com.mxdx.edu.util.RedisUtil;
import com.mxdx.edu.util.ServletUtil;
import com.mxdx.edu.util.SessionUtil;

/**
 * 拦截器
 * 
 * @author wangyuan
 * @date 2016-11-24 13:37
 *
 */
@Component
public class AuthInterceptor extends BaseInterceptor {

    private AppLogger logger = new AppLogger(AuthInterceptor.class);

    @Resource
    private IStudentService studentService;

    @Resource
    private SessionUtil sessionUtil;
    @Resource
    protected IUserJobBasisSeekerService userJobBasisSeekerService;
    @Resource
    protected IUserJobSeekerService userJobSeekerService;

    @Resource
    private ISalesManInfoService salesManInfoService;

    @Resource
    private RedisUtil redisUtil;

    //推荐报名
    private static String RECOMMENDENROLL_URL = "/continuingEducation/auth/recommendEnroll";

    //到校学习
    private static String ENROLLMENTREPORT_URL = "/continuingEducation/auth/enrollmentReport";

    //辅导课程
    private static String TOCURRICULUM_URL = "/curriculum/auth/toCurriculum";

    //课堂在线
    private static String COURSEONLINE_URL = "/curriculum/auth/courseOnLine";

    private static String JXJY_INDEX_URL = "/public/jxjyIndex";

    private static String SALES_MAN_INFO_URL = "/auth/salesManInfo";

    private static String RECRUIT_MODIFY_PWD_URL = "/edu/auth/recruitModifyPwd";

    private static String DO_MODIFY_PWD_URL = "/edu/auth/doModifyPwd";

    private static String DO_MODIFY_PWD_BY_MAP_URL = "/edu/auth/doModifyPwdByMap";

    private static String recommendCompanyDeatil_URL = "/auth/salesManInfo/recommendCompanyDetail";

    private static String URL = "/edu/static/qzzp";

    @SuppressWarnings("unchecked")
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        logger.entry(request.getRemoteAddr(), "AuthInterceptor preHandle");
        String toUrl = request.getServletPath();
        String type = ServletUtil.getParameterStr(request, "type", "");

        //获取session
//        String phoneNumber  = (String)request.getSession().getAttribute(StaticConstants.USER_SESSION_KEY);
//        String phoneNumber  = request.getHeader(StaticConstants.USER_SESSION_KEY);
        try {
            //证书跳转到此 获取token
            String token = ServletUtil.getParameterStr(request, "token", "");
            if("".equals(token))
             token = sessionUtil.getTokenSession(request);
            Object object = redisUtil.get(token);
            String studenttype = request.getParameter("studentType");
            if(object == null && (String.valueOf(StudentTypeEnums.SALES_MAN.getCode()).equals(studenttype) || SALES_MAN_INFO_URL.equals(toUrl) || recommendCompanyDeatil_URL.equals(toUrl))){
                String url = "/edu/public/salesManLogin?toUrl="+toUrl;
                response.sendRedirect(url);
                return false;
            }

            if(object == null && !JXJY_INDEX_URL.equals(toUrl)){
                String url = "/edu/public/toLogin?toUrl="+toUrl;
                response.sendRedirect(url);
                return false;
            }

            if(object != null && (SALES_MAN_INFO_URL.equals(toUrl) || recommendCompanyDeatil_URL.equals(toUrl) || RECRUIT_MODIFY_PWD_URL.equals(toUrl) || DO_MODIFY_PWD_URL.equals(toUrl) || DO_MODIFY_PWD_BY_MAP_URL.equals(toUrl))){
//                response.sendRedirect(toUrl);
                return true;
            }


            if(object == null && JXJY_INDEX_URL.equals(toUrl)){
                return true;
            }

            /**
             * 校验缓存中的状态是否与数据库一致，不一致则跳转到登录页面
             */
            String studentType ;
            if(object != null){
                Map<String, Object> map = (Map<String, Object>) object;
                String phoneNumber = CommonUtils.getStrValueFromMap(map, "phoneNumber", "");
                Map<String, Object> stuMap = studentService.findMapByPhoneNumber(phoneNumber);
                studentType = CommonUtils.getStrValueFromMap(stuMap, "studentType", "0");
                String studentTypes = CommonUtils.getStrValueFromMap(map, "studentType", "0");
                if(Integer.valueOf(studentType) != Integer.valueOf(studentTypes)){
                    redisUtil.delete(token);
                    String url = "/edu/public/toLogin";
                    //如果是业务员 跳转到业务员登录
                    if(StudentTypeEnums.SALES_MAN.getCode() == Integer.valueOf(studentTypes)){
                        url = "/edu/public/salesManLogin";
                    }
                    response.sendRedirect(url);
                    return false;
                }
            }
            if("1".equals(type)) {
            	String url = "/personnelWork/auth/applyJob";
                response.sendRedirect(url);
                return false;
            }
            //证书跳转到此
            if("3".equals(type)){
                String studentId = ServletUtil.getParameterStr(request, "studentId", "");
                String classId= ServletUtil.getParameterStr(request, "classId", "");
                String url = "/personnelWork/auth/applyJob?classId="+classId;
                //Map<String, Object> userJobBasisMap = userJobBasisSeekerService.findBasisSeekByStudentId(studentId);
                //String jobBaseSeekId= CommonUtils.getStrValueFromMap(userJobBasisMap, "id", "");
                //UserJobSeekerInfo userJobSeekerInfo=new UserJobSeekerInfo();
                //userJobSeekerInfo.setUserJobBasisId(jobBaseSeekId);
                //userJobSeekerService.findJobSeekerMapByMap(userJobMap);
                //jobSeekerId
                HttpSession session = request.getSession();
                    session.setAttribute(StaticConstants.USER_SESSION_KEY, token);
                response.sendRedirect(url);
                return false;
            }
            if(object != null && JXJY_INDEX_URL.equals(toUrl)){
                Map<String, Object> map = (Map<String, Object>) object;
                studentType = CommonUtils.getStrValueFromMap(map, "studentType", "0");
                if(StudentTypeEnums.TOURISTS.getCode() == Integer.valueOf(studentType) || StudentTypeEnums.REGISTER_STUDENTS.getCode() == Integer.valueOf(studentType)){
                    return true;
                }
//                String url = "/auth/successIndex";
//                response.sendRedirect(url);
//                return false;
            }

            //登录状态
            if(object != null){
                Map<String, Object> map = (Map<String, Object>) object;
                studentType = CommonUtils.getStrValueFromMap(map, "studentType", "0");
                //在校生
                if(StudentTypeEnums.ENROLLED_STUDENTS.getCode() == Integer.valueOf(studentType)){
                    String url = null;
                    //到校学习、辅导课程跳到我的班级
                    if(ENROLLMENTREPORT_URL.equals(toUrl) || TOCURRICULUM_URL.equals(toUrl)){
                        url = "/internal/auth/myClass";
                        response.sendRedirect(url);
                        return false;
                    }
                }
            }

            Map<String, Object> studentMap = (Map<String, Object>)object;
           /* String studentType = CommonUtils.getStrValueFromMap(studentMap, "studentType", "");
            //业务员
            if(StudentTypeEnums.SALES_MAN.getCode() == Integer.valueOf(studentType)) {
            	Map<String, Object> findSalesManMap = new HashMap<>();
            	String studentId = CommonUtils.getStrValueFromMap(studentMap, "id", "");
            	findSalesManMap.put("studentId", studentId);
            	Map<String, Object> salesMap = salesManInfoService.findMapByMap(findSalesManMap);
            	if(salesMap != null) {
            		String salesManType = CommonUtils.getStrValueFromMap(salesMap, "salesManType", "");
            		String url = "/auth/salesManInfo?salesManType="+salesManType;//+"&salesMap="+ JSONObject.toJSONString(salesMap)
                    response.sendRedirect(url);
                    return false;
            	}
            }*/
            String phoneNumber  = CommonUtils.getStrValueFromMap(studentMap, "phoneNumber", "");
            //手机号为空则直接跳转登录页面
            if(phoneNumber != null){
                //手机号不为空查询用户信息
                Map<String, Object> map = studentService.findMapByPhoneNumber(phoneNumber);
                if(map == null){
                    logger.doInfo("通过手机号,未找到用户信息:", phoneNumber);
                    String url = "/edu/public/toLogin?toUrl="+toUrl;
                    response.sendRedirect(url);
                    return false;
                }
                if(ENROLLMENTREPORT_URL.equals(toUrl) && map != null){
//                String url = "/continuingEducation/auth/enrollmentReport";
//                response.sendRedirect(url);
                  return true;
                }
                return true;
            }
            logger.info("==============>AuthInterceptor");
        }catch (Exception e){
            logger.error(e);
        }
        String url = "/edu/public/toLogin?toUrl="+toUrl;
        response.sendRedirect(url);
        return false;
    }
}
